package com.api.user.service.impl;

import com.api.user.dao.UserFollowMapper;
import com.api.user.model.UserFollow;
import com.api.user.service.UserFollowService;
import com.api.core.service.AbstractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import com.api.common.JSONUtils;
import com.api.core.response.Result;
import com.api.core.response.ResultGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * Created by wanghuiwen on 2021/03/29.
 */
@Service
@Transactional
public class UserFollowServiceImpl extends AbstractService<UserFollow> implements UserFollowService {
    @Resource
    private UserFollowMapper userFollowMapper;

    @Override
    public Result list(Boolean me, Long uid, Long userId, String order, Integer page, Integer size){
        Map<String, Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("uid",uid);
        Map<String, Object> orderParams = JSONUtils.json2map(order);
        for (String key : orderParams.keySet()) {
                if (orderParams.get(key) != null && orderParams.get(key).equals("ascending")) orderParams.put(key, "asc");
                if (orderParams.get(key) != null && orderParams.get(key).equals("descending")) orderParams.put(key, "desc");
        }

        if(me){
            PageHelper.startPage(page, size);
            List<Map<String, Object>> res = userFollowMapper.listByFollowMe(params, orderParams);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(res);
            return ResultGenerator.genSuccessResult(pageInfo);
        }else{
            PageHelper.startPage(page, size);
            List<Map<String, Object>> res = userFollowMapper.listByMeFollow(params, orderParams);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(res);
            return ResultGenerator.genSuccessResult(pageInfo);
        }


    }

    @Override
    public void add(Long userId,Long fansId) {
        UserFollow follow = new UserFollow();
        follow.setCreateTime(new Date().getTime());
        follow.setIdolId(userId);
        follow.setFansId(fansId);
        follow.setState(1);
        this.save(follow);
    }

    @Override
    public void remove(Long userId,Long fansId) {
        UserFollow follow = userFollowMapper.findByUserIdAndFansId(userId,fansId);
        follow.setState(2);
        this.deleteById(follow);
    }
}
